package com.ziyun.job.modules.job.task.seller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ziyun.erp.modules.capital.service.MerchantOrderAccountService;
import com.ziyun.erp.modules.material.entity.StoreMaterialCostCaculateRecordEntity;
import com.ziyun.erp.modules.material.service.StoreMaterialCostCaculateRecordService;
import com.ziyun.erp.modules.order.service.OrderInfoService;
import com.ziyun.erp.modules.supp.entity.SellerInfoEntity;
import com.ziyun.erp.modules.supp.service.SellerInfoService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author guizhao
 * @Description: 自营门店库存成本计算
 *  1.计算逻辑：加权平均        单价 = （期初库存数量 * 期初成本 + 入库数量 * 入库成本 - 出库数量 * 出库成本  ）
 *                                      ÷ ( 期初库存数量 + 入库成本 - 出库数量)
 *  2.按月计算
 * @date 2018-12-26 16:27
 */
@Slf4j
@Component("sellerMaterialCostCaculateTask")
public class SellerMaterialCostCaculateTask {
    private  static  Logger logger = LoggerFactory.getLogger(SellerMaterialCostCaculateTask.class);

    // 初始成本计算周期时间 （年月）
    private  static final Integer startCostCycle = 20190101;

    @Autowired
    private SellerInfoService sellerInfoService;
    @Autowired
    private StoreMaterialCostCaculateRecordService storeMaterialCostCaculateRecordService;

    /**
     * 自营门店库存成本计算
     */
    public void sellerMaterialCostCaculate(){
        // 参与成本计算 自营门店ID
        Integer[] sellerIdList = {2,4,6,10,12,14,15,16};

        log.info("====================自营门店库存成本计算 计划任务开始===================");

        // 查询上一次计算周期
        StoreMaterialCostCaculateRecordEntity storeMaterialCostCaculateRecordEntity = storeMaterialCostCaculateRecordService
                .selectOne(new EntityWrapper<StoreMaterialCostCaculateRecordEntity>()
                        .orderBy("cost_cycle",false)
                        .last("limit 1")
                );

        if (storeMaterialCostCaculateRecordEntity == null){
            storeMaterialCostCaculateRecordEntity = new StoreMaterialCostCaculateRecordEntity();
            storeMaterialCostCaculateRecordEntity.setCaculateStartTime(new Date());
            storeMaterialCostCaculateRecordEntity.setCostCycle(startCostCycle);
        }

        for (int i=0; i<sellerIdList.length; i++){
            SellerInfoEntity sellerInfoEntity = sellerInfoService.selectById(sellerIdList[i]);

            log.info("==================== 开始计算 门店："+sellerInfoEntity.getSellerName()+" 库存成本 ===================");

            log.info("==================== 门店："+sellerInfoEntity.getSellerName()+" 库存成本计算结束 ===================");
        }
        storeMaterialCostCaculateRecordEntity.setCaculateEndTime(new Date());

        log.info("====================自营门店库存成本计算 计划任务完成===================");
    }


}
